$(document).ready(function() {
    // Initialize Bootstrap tooltips
    try {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        });
        
        // Initialize Bootstrap popovers
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl)
        });
    } catch (e) {
        console.log("Bootstrap components initialization skipped:", e.message);
    }
    
    // Carousel auto-slide
    try {
        // Use Bootstrap 5 carousel initialization with explicit interval
        document.addEventListener('DOMContentLoaded', function() {
            var carouselElement = document.querySelector('#mainCarousel');
            if (carouselElement) {
                var carousel = new bootstrap.Carousel(carouselElement, {
                    interval: 5000,
                    wrap: true,
                    touch: true
                });
                
                // Manually trigger initial cycle if needed
                setTimeout(function() {
                    carousel.cycle();
                }, 500);
            }
        });
    } catch (e) {
        console.log("Carousel initialization skipped:", e.message);
        // Fallback carousel implementation
        var carousels = document.querySelectorAll('.carousel');
        if (carousels.length > 0) {
            setInterval(function() {
                carousels.forEach(function(carousel) {
                    var items = carousel.querySelectorAll('.carousel-item');
                    var activeItem = carousel.querySelector('.carousel-item.active');
                    if (activeItem && items.length > 1) {
                        var activeIndex = Array.from(items).indexOf(activeItem);
                        var nextIndex = (activeIndex + 1) % items.length;
                        activeItem.classList.remove('active');
                        items[nextIndex].classList.add('active');
                    }
                });
            }, 5000);
        }
    }
    
    // Handle quantity controls
    $('.quantity-minus').click(function() {
        var input = $(this).closest('.quantity-control').find('.quantity-input');
        var value = parseInt(input.val());
        if (value > 1) {
            input.val(value - 1);
        }
    });
    
    $('.quantity-plus').click(function() {
        var input = $(this).closest('.quantity-control').find('.quantity-input');
        var value = parseInt(input.val());
        var max = parseInt(input.attr('max') || 99);
        if (value < max) {
            input.val(value + 1);
        }
    });
    
    // Add to cart button
    $('.add-to-cart').click(function() {
        var productId = $(this).data('product-id');
        
        $.ajax({
            url: 'cart/add',
            type: 'POST',
            data: {
                productId: productId,
                quantity: 1
            },
            success: function(response) {
                if (response.success) {
                    alert('已成功加入购物车');
                } else {
                    alert(response.message || '加入购物车失败');
                }
            },
            error: function() {
                alert('加入购物车失败，请稍后再试');
            }
        });
    });
    
    // Search form validation
    $('#search-form').submit(function(e) {
        var keyword = $('#search-input').val().trim();
        if (keyword === '') {
            e.preventDefault();
            alert('请输入搜索关键词');
        }
    });
    
    // Sticky header
    try {
        var header = $('.site-header');
        if (header.length > 0) {
            var headerOffset = header.offset().top;
            
            $(window).scroll(function() {
                if ($(window).scrollTop() > headerOffset) {
                    header.addClass('sticky');
                } else {
                    header.removeClass('sticky');
                }
            });
        }
    } catch (e) {
        console.log("Sticky header initialization skipped:", e.message);
    }
    
    // Back to top button
    try {
        $(window).scroll(function() {
            var backToTop = $('#back-to-top');
            if (backToTop.length > 0) {
                if ($(this).scrollTop() > 300) {
                    backToTop.fadeIn();
                } else {
                    backToTop.fadeOut();
                }
            }
        });
        
        $('#back-to-top').click(function() {
            $('html, body').animate({scrollTop: 0}, 800);
            return false;
        });
    } catch (e) {
        console.log("Back to top initialization skipped:", e.message);
    }
}); 